package com.wenjh.jdmzt.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import java.util.Iterator;

/**
 * 字符串处理类
 *
 */
public class StringUtils {
	/**
	 * 判断字符串是否为空
	 * @param str
	 * @return
	 */
	public static boolean isEmpty(CharSequence str){
		if(str == null || "".equals(str)) return true;
		return false;
	}
	
	/**
	 * 将字符串转换成字符串组数,按照指定的标记进行转换
	 */
	public static String[] str2Arr(String value, String tag) {
		if (!isEmpty(value)) {
			return value.split(tag);
		}
		return null;
	}

	/**
	 * 将一个字符串数组组合成一个以指定分割符分割的字符串
	 */
	public static String join(Object[] array, String separator) {
		if (array == null) {
			return null;
		}
		return join(array, separator, "", 0, array.length);
	}
	
	/**
	 * 将一个字符串数组组合成一个以指定分割符分割的字符串
	 */
	public static String join(Object[] array, String ch, String separator) {
		if (array == null) {
			return null;
		}
		return join(array, separator, ch, 0, array.length);
	}

	/**
	 * 将一个字符串数组的某一部分组合成一个以指定分割符分割的字符串
	 */
	public static String join(Object[] array, String separator, String ch, int startIndex,
			int endIndex ) {
		if (array == null) {
			return null;
		}
		if (separator == null) {
			separator = "";
		}
        
		// 开始位置大于结束位置
		int bufSize = (endIndex - startIndex);
		if (bufSize <= 0) {
			return "";
		}

		bufSize *= ((array[startIndex] == null ? 16 : array[startIndex]
				.toString().length()) + separator.length());

		StringBuffer buf = new StringBuffer(bufSize);

		for (int i = startIndex; i < endIndex; i++) {
			if (i > startIndex) {
				buf.append(separator);
			}
			if (array[i] != null) {
				buf.append(ch+array[i]+ch);
			}
		}
		return buf.toString();
	}

	/**
	 * 将一个集合组合成以指定分割符分割的字符串
	 */
	public static String join(Collection collection, String separator) {
		if (collection == null) {
			return "";
		}
		return join(collection.iterator(), separator);
	}

	/**
	 * 根据迭代器，迭代的元素将组合成以指定分割符分割的字符串
	 */
	public static String join(Iterator iterator, String separator) {

		// 空的迭代器，返回 null
		if (iterator == null) {
			return null;
		}
		// 空元素，返回 null
		if (!iterator.hasNext()) {
			return "";
		}

		Object first = iterator.next();
		// 只有一个元素
		if (!iterator.hasNext()) {
			if (first != null) {
				return first.toString();
			} else {
				return "";
			}
		}

		StringBuffer buf = new StringBuffer(256);
		if (first != null) {
			buf.append(first);
		}

		while (iterator.hasNext()) {
			if (separator != null) {
				buf.append(separator);
			}
			Object obj = iterator.next();
			if (obj != null) {
				buf.append(obj);
			}
		}

		return buf.toString();
	}
	
	/**
	 * 将集合元素转换成字符串："'qq','aa','cc'"
	 */
	public static String Conll2StringWithSingleGuotes(@SuppressWarnings("rawtypes") Collection collection, String separator) {
		if (collection == null) {
			return null;
		}
		Iterator iterator = collection.iterator();
		
		// 空的迭代器，返回 null
		if (iterator == null) {
			return null;
		}
		// 空元素，返回 null
		if (!iterator.hasNext()) {
			return "";
		}

		Object first = iterator.next();
		// 只有一个元素
		if (!iterator.hasNext()) {
			if (first != null) {
				return "'" + first.toString() + "'";
			} else {
				return "";
			}
		}

		StringBuffer buf = new StringBuffer(256);
		if (first != null) {
			buf.append("'" + first + "'");
		}

		while (iterator.hasNext()) {
			if (separator != null) {
				buf.append(separator);
			}
			Object obj = iterator.next();
			if (obj != null) {
				buf.append("'" + obj + "'");
			}
		}

		return buf.toString();
	}
	
	
	public static String escapeUnicode(String src) {
		int i;
		char j;
		StringBuffer tmp = new StringBuffer();
		tmp.ensureCapacity(src.length() * 6);
		for (i = 0; i < src.length(); i++) {
			j = src.charAt(i);
			if (Character.isDigit(j) || Character.isLowerCase(j)
					|| Character.isUpperCase(j))
				tmp.append(j);
			else if (j < 256) {
				tmp.append("%");
				if (j < 16)
					tmp.append("0");
				tmp.append(Integer.toString(j, 16));
			} else {
				tmp.append("%u");
				tmp.append(Integer.toString(j, 16));
			}
		}
		return tmp.toString();
	}
	
	public static String unescapeUnicode(String src) {
		StringBuffer tmp = new StringBuffer();
		tmp.ensureCapacity(src.length());
		int lastPos = 0, pos = 0;
		char ch;
		while (lastPos < src.length()) {
			pos = src.indexOf("%", lastPos);
			if (pos == lastPos) {
				if (src.charAt(pos + 1) == 'u') {
					ch = (char) Integer.parseInt(
							src.substring(pos + 2, pos + 6), 16);
					tmp.append(ch);
					lastPos = pos + 6;
				} else {
					ch = (char) Integer.parseInt(
							src.substring(pos + 1, pos + 3), 16);
					tmp.append(ch);
					lastPos = pos + 3;
				}
			} else {
				if (pos == -1) {
					tmp.append(src.substring(lastPos));
					lastPos = src.length();
				} else {
					tmp.append(src.substring(lastPos, pos));
					lastPos = pos;
				}
			}
		}
		return tmp.toString();
	}

	
	private static final int HOURS_OF_DAY = 24;
	private static final int MINUTES_OF_HOUR = 60;
	private static final int SECONDS_OF_MINUTE = 60;
	private static long CalPassedDay(long totalSec) {
		long result = totalSec / (HOURS_OF_DAY * MINUTES_OF_HOUR * SECONDS_OF_MINUTE);
		return result;
	}
	private static long CalPassedHour(long totalSec) {
		long result = (totalSec % (HOURS_OF_DAY * MINUTES_OF_HOUR * SECONDS_OF_MINUTE)) / (MINUTES_OF_HOUR * SECONDS_OF_MINUTE);
		return result;
	}
	private static long CalPassedMin(long totalSec) {
		long result = ((totalSec % (HOURS_OF_DAY * MINUTES_OF_HOUR * SECONDS_OF_MINUTE)) % (MINUTES_OF_HOUR * SECONDS_OF_MINUTE)) / SECONDS_OF_MINUTE;
		return result;
	}
	private static long CalPassedSec(long totalSec) {
		long result = ((totalSec % (HOURS_OF_DAY * MINUTES_OF_HOUR * SECONDS_OF_MINUTE)) % (MINUTES_OF_HOUR * SECONDS_OF_MINUTE)) % SECONDS_OF_MINUTE;
		return result;
	}
	
	/**
	 * 根据传入的时间戳返回时间
	 * @param stmap
	 * @return
	 */
	public static String TimeStampToTime(final long creat_stmap, final long server_stamp){
		String result = "";
		long passedTotalSeconds = server_stamp - creat_stmap;
		if(passedTotalSeconds <= 0){
			result = "1秒钟前";
			return result;
		}
		long passedDay = CalPassedDay(passedTotalSeconds);
		long passedHour = CalPassedHour(passedTotalSeconds);
		long passedMin = CalPassedMin(passedTotalSeconds);
		long passedSec = CalPassedSec(passedTotalSeconds);
		if(passedDay > 0){
			result = new Long(passedDay).toString() + "天前";
			return result;
		}
		if(passedHour > 0){
			result = new Long(passedHour).toString() + "小时前";
			return result;
		}
		if(passedMin > 0){
			result = new Long(passedMin).toString() + "分钟前";
			return result;
		}
		if(passedSec > 0){
			result = new Long(passedSec).toString() + "秒前";
			return result;
		}
		return result;
	}
	
	
	public static String md5(String s) {
	    try {
	        // Create MD5 Hash
	        MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
	        digest.update(s.getBytes());
	        byte messageDigest[] = digest.digest();
	        
	        // Create Hex String
	        StringBuffer hexString = new StringBuffer();
	        for (int i=0; i<messageDigest.length; i++) {
	        	String h = Integer.toHexString(0xFF & messageDigest[i]);
	        	while (h.length()<2) h = "0" + h;
	            hexString.append(h);
	        }
	        return hexString.toString();
	        
	    } catch (NoSuchAlgorithmException e) {
	    }
	    return s;
	}
	
	public static String removeEmoji(String string) {
		if(StringUtils.isEmpty(string)) {
			return "";
		}
		return string.trim().replaceAll("([\ue000-\ue5ff])", "");
	}
	
	
	/**
	 * 一个字符串是否包含另一字符串
	 * @param str1
	 * @param str2
	 * @return
	 */
	public static boolean contains(String str1, String str2) {
		return str1.contains(str2) || str2.contains(str1);
	}
	
	
	/**
	 * 一个字符串是以另一字符串开头
	 * @param str1
	 * @param str2
	 * @return
	 */
	public static boolean startsWith(String str1, String str2) {
		return str1.startsWith(str2) || str2.startsWith(str1);
	}
	
}
